package juc2.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock提供了公平锁和非公平锁两种模式公平锁与非公平锁的演示
 */
public class FairLockDemo {
    // 公平锁：true表示公平模式
    private static final Lock FAIR_LOCK = new ReentrantLock(true);
    // 非公平锁：默认模式
    private static final Lock UNFAIR_LOCK = new ReentrantLock(false);

    public static void main(String[] args) {
        System.out.println("=== 公平锁测试 ===");
        testLock(FAIR_LOCK);

        System.out.println("\n=== 非公平锁测试 ===");
        testLock(UNFAIR_LOCK);
    }

    private static void testLock(Lock lock) {
        // 创建5个线程，每个线程尝试获取锁5次
        for (int i = 0; i < 5; i++) {
            final int threadId = i;
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {//尝试获取锁5次
                    lock.lock();
                    try {
                        // 打印当前获取到锁的线程ID
                        System.out.printf("线程%d 获取到锁\n", threadId);
                        // 短暂休眠，模拟处理时间
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    } finally {
                        lock.unlock();
                    }

                    // 短暂休眠，让其他线程有机会竞争锁
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }).start();
        }

        // 等待所有线程执行完成
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

